package pers.xiaojun.boot.mybatis.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import pers.xiaojun.boot.common.biz.system.tenant.TenantCommonApi;
import pers.xiaojun.boot.security.pojo.AuthUserDetails;
import pers.xiaojun.boot.mybatis.core.enitiy.BaseEntity;
import pers.xiaojun.boot.security.util.SecurityUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 自动填充字段处理器
 *
 * @author xiaojun
 * @since 2025-10-03
 */
@Slf4j
@RequiredArgsConstructor
public class MyBatisMetaObjectHandler implements MetaObjectHandler {

    private final static String UPDATE_TIME_COLUMN = "updateTime";
    private final static String UPDATER_COLUMN = "updater";

    /**
     * 插入操作时的填充方法
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseDO = (BaseEntity) metaObject.getOriginalObject();

            if (Objects.isNull(baseDO.getCreateTime())) {
                baseDO.setCreateTime(LocalDateTime.now());
            }
            if (Objects.isNull(baseDO.getUpdateTime())) {
                baseDO.setUpdateTime(LocalDateTime.now());
            }
            String userId = getUserId();
            if (Objects.nonNull(userId)) {
                if (Objects.isNull(baseDO.getCreator())) {
                    baseDO.setCreator(userId);
                }
                if (Objects.isNull(baseDO.getUpdater())) {
                    baseDO.setUpdater(userId);
                }
            }
        }
    }

    /**
     * 更新操作时的填充方法
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTimeObj = getFieldValByName(UPDATE_TIME_COLUMN, metaObject);
        if (Objects.isNull(updateTimeObj)) {
            setFieldValByName(UPDATE_TIME_COLUMN, LocalDateTime.now(), metaObject);
        }

        String userId = getUserId();
        if (Objects.nonNull(userId)) {
            Object updaterObj = getFieldValByName(UPDATER_COLUMN, metaObject);
            if (Objects.isNull(updaterObj)) {
                setFieldValByName(UPDATER_COLUMN, userId, metaObject);
            }
        }
    }


    /**
     * 获取当前用户名
     *
     * @return 用户名
     */
    private String getUserId() {
        AuthUserDetails user = SecurityUtils.getUser();
        return user == null ? null : user.getId().toString();
    }

}
